import { mapMutations, mapActions, mapState } from "vuex";
import _ from "lodash";
import { typeClassName } from "@/pages/config/classNameMap";
import dayjs from "dayjs";
export default {
  data() {
    return {
      vms: {}, //页面组件vue实例
      models: {
        //模型

        dept: {
          ...typeClassName["dept"],
        },
        person: {
          ...typeClassName["person"],
        },
        job: {
          ...typeClassName["job"],
        },
      },
      onlyRead: false,
      departmentOptions: [],
      seniorJobOptions: [],
      roleList: [],
      dataSet: {
        //数据集
        tableData: [],
        formData: {},
      },
    };
  },
  provide() {
    return {
      anc: this,
    };
  },
  computed: {},
  created() {
    Object.keys(this.models).map((k) => {
      this.models[k].clz = this.$modelObject.create(this.models[k].modelType);
      this.models[k].clzs = this.$modelObject.create(
        this.models[k].modelType + "Collection"
      );
    });
  },
  mounted() {
    this.$nextTick(() => {
      this.getdepartment();
      this.getRoleData();
      this.setOptionsByHier("job", this.models.job.clz, "jobOptions", {
        label: "sf_name",
        value: "sf_code",
      });
      if (process.env.NODE_ENV === "development") {
        console.log(this);
      }
    });
  },
  methods: {
    /**
     *
     * @param {分页} pageNavigation
     * @param {筛选条件} filter
     * @param {*} orderBy
     * 页面加载方法
     */
    loadPage(pageNavigation, filter) {
      let newFilter = {
        ...filter,
        className: this.models.job.className,
        type: this.models.job.type,
      };
      this.vms.postTable.loading = true;
      this._$queryByPage(
        this.models["job"].clzs,
        pageNavigation,
        newFilter,
        "",
        "",
        false
      ).then((res) => {
        this.vms.postTable.loading = false;
        // 整理数据 数据格式
        this.dataSet.tableData = [];
        this.models["job"].clzs.valueRecords[0].hier.content.forEach(
          (d) => {
            if (d.name != "根节点") {
              this.dataSet.tableData.push({
                ...d,
                ...d.values,
              });
            }
          }
        );
        this.vms.postTable.pageNavigation.total =
          this.models["job"].clzs.total - 1;
      });
    },

    /**
     * 人员管理新增
     */
    handleCreate() {
      this.vms.createModal.show = true;
      this.onlyRead = false;
      this.seniorJobOptions = this.jobOptions;
      this.dataSet.formData = this.$modelObject.getTpl(
        this.models.job.modelType
      ); // 这是一个整理接口数据JSON格式的方法
    },
    /**
     *
     * @param {*} row
     * 人员管理查看
     */
    handleDetail(row) {
      console.log(row);
      this.vms.detailModal.show = true;
      this.seniorJobOptions = this.jobOptions;
      this.dataSet.formData = row;
      this.onlyRead = true;
    },
    /**
     *
     * @param {*} row
     * 人员管理编辑
     */
    handleEdit(row) {
      this.vms.editModal.show = true;
      this.seniorJobOptions = this.jobOptions;
      this.onlyRead = false;
      this.dataSet.formData = row;
    },
    /**
     *
     * @param {行数据} row
     * @param {索引} index
     * 人员管理删除数据
     */
    handleDelete(row, index) {
      // let _this = this;

      this._$deleteConfirm(() => {
        this.$api.HierInstanceDeleteHier([row.id]).then((flag) => {
          this.vms.postTable.pageNavigation.pageNumber = 1;
          this.loadPage(this.vms.postTable.pageNavigation, {}, "", "", false);
        });
      });
    },
    /**
     *
     * @param {行数据} selection
     */
    handleDeleteMultiple(selection) {
      this._$deleteConfirm(() => {
        let ids = selection.map((item) => String(item.id));
        this.$api.HierInstanceDeleteHier(ids).then((res) => {
          this.vms.postTable.pageNavigation.pageNumber = 1;
          this.loadPage(this.vms.postTable.pageNavigation, {});
        });
      });
    },

    // 创建人员管理提交
    createModalOk() {
      // this.vms.createView.validate((valid) => {
      this._$validateAll([this.vms.createView], (valid) => {
        if (valid) {
          let newData = {
            values: this.dataSet.formData.values,
            containerModel: this.models.job.modelType,
            containerId: this.models["job"].clzs.valueRecords[0].id,
            parentId: "root",
          };

          this.$api.HierInstanceSaveHier([newData]).then((flag) => {
            this.vms.postTable.pageNavigation.pageNumber = 1;
            this.loadPage(this.vms.postTable.pageNavigation, {}, "", "", false);
            this.vms.createModal.show = false;
          });
        } else {
          this.$Message.info("请填写必填内容");
        }
      });
    },

    editModalOk() {
      this.vms.editView.validate((valid) => {
        if (valid) {
          let newData = {
            values: this.dataSet.formData.values,
            containerModel: this.models.job.modelType,
            containerId: this.models["job"].clzs.valueRecords[0].id,
            parentId: "root",
            id:this.dataSet.formData.id
          };

          this.$api.HierInstanceSaveHier([newData]).then((flag) => {
            this.vms.postTable.pageNavigation.pageNumber = 1;
            this.loadPage(this.vms.postTable.pageNavigation, {}, "", "", false);
            this.vms.editModal.show = false;
          });
        } else {
          this.$Message.info("请填写必填内容");
        }
      });
    },
    getdepartment() {
      let filter = {
        className: this.models.dept.className,
        type: this.models.dept.type,
      };
      let newFilter = "";
      if (this.tools.isReal(filter)) {
        newFilter = this.models.dept.clzs.util.getFilter(filter);
      }
      this.models.dept.clzs.query(newFilter).then((flag) => {
        if (flag) {
          let departmentOptions = [];
          departmentOptions = this.getChildren(
            "root",
            this.models.dept.clzs.records[0].hier.content
          );
          this.departmentOptions = departmentOptions;
        } else {
          this.departmentOptions = [];
        }
      });
    },
    getChildren(parentId, data) {
      let children = [];
      let list = data.filter((item) => item.parentId === parentId);
      list.map((item) => {
        if (
          !!item.pointer &&
          item.pointer.className === typeClassName["person"].className
        ) {
          return;
        }
        children.push({
          title: item.values.sf_name ? `${item.values.sf_name}` : item.name,
          label: item.values.sf_name ? `${item.values.sf_name}` : item.name,
          id: item.id,
          value: item.id,
          code: item.values.sf_code,
          parentId: item.parentId,
          contextmenu: true,
          data: item,
          pointer: item.pointer,
          children: this.getChildren(item.id, data),
          disabled:
            !!item.pointer &&
            item.pointer.className === this.models.person.className,
        });
      });
      return children;
    },
    setOptionsByHier(
      classMapName,
      classObject,
      optionName,
      optionConfig = { label: "sf_name", value: "sf_code" }
    ) {
      let filter = {
        className: this.models[classMapName].className,
        type: this.models[classMapName].type,
      };
      let newFilter = "";
      if (this.tools.isReal(filter)) {
        newFilter = classObject.util.getFilter(filter);
      }
      let statusOptions = [];
      return classObject.query(newFilter).then((flag) => {
        if (flag) {
          statusOptions = classObject.record.hier.content.map((d) => {
            let option = {};
            for (let key in optionConfig) {
              option[key] = d.values[optionConfig[key]];
            }
            return option;
          });
        } else {
          statusOptions = [];
        }
        this[optionName] = statusOptions;
      });
    },
    getRoleData() {
      // 下面的 params 是获取的表单查询参数
      let condition = "";
      this.$api.Role.queryByPage(1, 20, { condition })
        .then((res) => {
          let list = [];
          list = this._clone(res.records);

          this.roleList = list.map((d) => {
            return {
              label: d.roleName === null ? "" : d.roleName,
              value: d.roleCode === null ? "" : d.roleCode,
            };
          });
        })
        .finally(() => {
          this.loading = false;
        });
    },
    getSeniorOption(values) {
      this.seniorJobOptions = this.jobOptions.filter(
        (d) => d.value !== values.sf_code
      );
    },
  },
};
